﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IterateFolder
{
    public partial class frmMain : Form
    {
        #region Variables
        // These store the default text for textbox controls on form
        private string strDirectoryText, strSaveLocText, strSaveNameText;
        #endregion

        #region WinForm Stuff
        public frmMain()
        {
            // Required by WinForms to launch correctly
            InitializeComponent();
        }
        #endregion

        #region Load Event
        private void frmMain_Load(object sender, EventArgs e)
        {
            // Set default text for textboxes
            strDirectoryText = "Please Choose a Directory...";
            strSaveLocText = "Please Choose a Save Location...";
            strSaveNameText = "Please Choose a File Name to Save As...";
        }
        #endregion

        #region Custom Methods
        // Checks whether or not the textboxes are default or empty
        // and allows use of generate button accordingly
        private void CheckTextBoxes()
        {
            if (txtDirectory.Text == string.Empty || txtSaveLoc.Text == string.Empty || txtDirectory.Text == strDirectoryText || txtSaveLoc.Text == strSaveLocText)
            {
                btnGenerate.Enabled = false;
            }
            else
            {
                btnGenerate.Enabled = true;
            }
        }

        // Handles what happens when a textbox is currently in use
        private void txtEnter(TextBox textbox, string strDefaultText)
        {
            if (textbox.Text == strDefaultText)
            {
                textbox.Text = "";
                textbox.ForeColor = Color.Black;
            }

            CheckTextBoxes();
        }

        // Handles what happens when a textbox is de-activated (no longer in use)
        private void txtLeave(TextBox textbox, string strDefaultText)
        {
            if (textbox.Text == string.Empty)
            {
                textbox.Text = strDefaultText;
                textbox.ForeColor = Color.Red;
            }

            CheckTextBoxes();
        }

        // Handles creation, opening and selection of folder browser dialog
        private void OpenBrowserDialog(TextBox textBox, string defaultText)
        {
            // Allow program to open a dialog box to browse client's system
            DialogResult browse = this.fdrBrowser.ShowDialog();

            if (browse == DialogResult.OK)
            {
                string folder = this.fdrBrowser.SelectedPath;
                if (!(folder == string.Empty))
                {
                    textBox.ForeColor = Color.Black;
                    textBox.Text = folder;
                }
                else
                {
                    textBox.ForeColor = Color.Red;
                    textBox.Text = defaultText;
                }
            }

            // Check all text boxes & reset folder browser to default settings (includes root dir)
            CheckTextBoxes();
            fdrBrowser.Reset();
        }

        private void createFile()
        {
            try
            {
                // Setting up everything to write to a file
                DirectoryInfo dirInfo = new DirectoryInfo(@txtDirectory.Text);
                FileInfo[] Files = dirInfo.GetFiles("*.*");
                string txtToSave = "";

                // Generate the string that will be written
                foreach (FileInfo file in Files)
                {
                    txtToSave = txtToSave + file.Name.Substring(0, file.Name.LastIndexOf(".")) + Environment.NewLine;
                }

                // Get the path of the file to write to
                string strPath = Path.Combine(txtSaveLoc.Text, txtSaveName.Text);
                TextWriter textWriter = new StreamWriter(strPath);

                // Create the file if it doesn't already exist
                if (!(File.Exists(strPath)))
                {
                    File.Create(strPath);
                }

                // Write and close the operation
                textWriter.Write(txtToSave);
                textWriter.Close();
            }
            // Catch and exception regarding Input/Output (this 
            // includes writing to the file and creating a new file)
            catch (IOException ex)
            {
                MessageBox.Show("Error:" + ex,
                                "Unexpected Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
        #endregion

        #region Browse Buttons
        private void btnBrowseDir_Click(object sender, EventArgs e)
        {
            OpenBrowserDialog(txtDirectory, strDirectoryText);        
        }

        private void btnBrowseSaveLoc_Click(object sender, EventArgs e)
        {
            OpenBrowserDialog(txtSaveLoc, strSaveLocText);
        }
        #endregion

        #region TextBox Enter & Leave Events
        private void txtSaveName_Enter(object sender, EventArgs e)
        {
            if (txtSaveName.Text == strSaveNameText)
            {
                txtSaveName.Text = "";
            }

            txtSaveName.ForeColor = Color.Black;
        }

        private void txtSaveName_Leave(object sender, EventArgs e)
        {
            // This code checks whether or not the user has entered anything
            // and either sets default text if nothing entered, or adds '.txt'
            // onto the end of the string typed to allow creation of text files
            if (txtSaveName.Text == string.Empty)
            {
                txtSaveName.Text = strSaveNameText;
                txtSaveName.ForeColor = Color.Red;
            }
            else
            {
                if (!(txtSaveName.Text.EndsWith(".txt")))
                {
                    txtSaveName.Text = txtSaveName.Text + ".txt";
                }
            }
        }

        private void txtDirectory_Enter(object sender, EventArgs e)
        {
            txtEnter(txtDirectory, strDirectoryText);
        }

        private void txtDirectory_Leave(object sender, EventArgs e)
        {
            txtLeave(txtDirectory, strDirectoryText);
        }

        private void txtSaveLoc_Enter(object sender, EventArgs e)
        {
            txtEnter(txtSaveLoc, strSaveLocText);
        }

        private void txtSaveLoc_Leave(object sender, EventArgs e)
        {
            txtLeave(txtSaveLoc, strSaveLocText);
        }
        #endregion

        #region 'Generate' Button Code
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            // Error checking and prevention using multiple message boxes with warning text
            // instructing the user on how to proceed to make the program work
            if (!(Directory.Exists(txtDirectory.Text)) && !(Directory.Exists(txtSaveLoc.Text)))
            {
                MessageBox.Show("Both Directory & Save Location do not exist, please choose valid locations!", 
                                "Error: Invalid Directories", 
                                MessageBoxButtons.OK, 
                                MessageBoxIcon.Error);
            }
            else if (!(Directory.Exists(txtDirectory.Text)))
            {
                MessageBox.Show("Chosen Directory doesn't exist, choose another!", 
                                "Error: Invalid Directory", 
                                MessageBoxButtons.OK, 
                                MessageBoxIcon.Error);
            }
            else if (!(Directory.Exists(txtSaveLoc.Text)))
            {
                try
                {
                    Directory.CreateDirectory(@txtSaveLoc.Text);
                    createFile();
                }
                catch (DirectoryNotFoundException ex)
                {
                    MessageBox.Show("Location: '" + ex + "' is not a valid",
                                    "Error: Invalid Save Location",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }                
            }
            else if (txtSaveName.Text == string.Empty || txtSaveName.Text == strSaveNameText)
            {
                MessageBox.Show("No save name chosen, go back and enter one!", 
                                "Error: No Save Name chosen!", 
                                MessageBoxButtons.OK, 
                                MessageBoxIcon.Error);
            }
            else
            {
                createFile();
            }
        }
        #endregion
    }
}
